package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.http.lifecycle.ApplicationLifecycle;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.hjq.widget.layout.SettingBar;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.HandleListener;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.ProtocolSwitchResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AddDeviceBean;
import com.qiantu.phone.bean.TimeLimitBean;
import com.qiantu.phone.event.DeviceItemChangeEvent;
import com.qiantu.phone.event.DeviceListChangeEvent;
import com.qiantu.phone.event.RefreshControllerEvent;
import com.qiantu.phone.event.RefreshDeviceListEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.manager.ActivityManager;
import com.qiantu.phone.ui.adapter.EnviromentScrollAdapter;
import com.qiantu.phone.ui.adapter.LoadDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomBaudDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.BottomParityDialog;
import com.qiantu.phone.ui.dialog.BottomProtocolSwitchDialog;
import com.qiantu.phone.ui.dialog.BottomStopbitDialog;
import com.qiantu.phone.ui.dialog.BottomTimeLimitDialog;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.utils.AddDeviceParseUtil;
import com.qiantu.phone.utils.Constants;
import com.qiantu.phone.widget.StatusLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;

public class ControllerParameterActivity extends AppActivity {
    private String controllerSerialNo;
    private SettingBar itemBaud;
    private SettingBar itemParity;
    private SettingBar itemStopbit;
    private BottomBaudDialog mBottomBaudDialog;
    private BottomParityDialog mBottomParityDialog;
    private BottomStopbitDialog mBottomStopbitDialog;
    ControllerBean mControllerBean;
    String[] bauds;
    String[] checkTypes;
    String[] endMark;

    @Log
    public static void start(Context context, String controllerSerialNo) {
        Intent intent = new Intent(context, ControllerSettingActivity.class);
        intent.putExtra("controllerSerialNo", controllerSerialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contoller_parameter;
    }

    @Override
    protected void initView() {
        getTitleBar().setRightTitle(R.string.save);
        controllerSerialNo = getString("controllerSerialNo");
        itemBaud = findViewById(R.id.item_baud);
        itemParity = findViewById(R.id.item_parity);
        itemStopbit = findViewById(R.id.item_stopbit);
        setOnClickListener(itemBaud, itemParity, itemStopbit);
        bauds = new String[]{"2400","4800","9600","19200","38400","57600","115200"};
        checkTypes = new String[]{"None","Odd","Even"};
        endMark = new String[]{"1","1.5","2"};
    }

    @Override
    protected void initData() {
//        mControllerBean = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(controllerSerialNo);
        getSetting();
    }

    @Override
    public void onRightClick(View view) {
        LLHttpManager.setControllerSettings(this, controllerSerialNo, mControllerBean.getControllerSettingDto().getSettings(), new HttpCallback<HttpData<Void>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
                super.onSucceed(result);
                finish();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    private void getSetting(){
        LLHttpManager.getControllerSettings(this, controllerSerialNo, new HttpCallback<HttpData<ControllerBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<ControllerBean> result) {
                super.onSucceed(result);
                mControllerBean = result.getData();
                if(mControllerBean.getControllerSettingDto() != null && mControllerBean.getControllerSettingDto().getSettings() != null){
                    int baudsint = mControllerBean.getControllerSettingDto().getSettings().getBaudrate()-1;
                    if (baudsint < 0){
                        baudsint = 0;
                    }
                    int checkTypesint = mControllerBean.getControllerSettingDto().getSettings().getChecktype()-1;
                    if (checkTypesint < 0){
                        checkTypesint = 0;
                    }
                    int endMarkint = mControllerBean.getControllerSettingDto().getSettings().getEndmark()-1;
                    if (endMarkint < 0){
                        endMarkint = 0;
                    }
                    itemBaud.setRightText(bauds[baudsint]);
                    itemParity.setRightText(checkTypes[checkTypesint]);
                    itemStopbit.setRightText(endMark[endMarkint]);
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.item_baud:
                showBottomBaudDialog();
                break;
            case R.id.item_parity:
                showBottomParityDialog();
                break;
            case R.id.item_stopbit:
                showBottomStopbitDialog();
                break;
        }
    }

    private void showBottomBaudDialog() {
        if (mBottomBaudDialog == null) {
            mBottomBaudDialog = new BottomBaudDialog(getContext());
            mBottomBaudDialog.setLabel("波特率");
            mBottomBaudDialog.setDialogClickListener(new BottomBaudDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int value) {
                    mBottomBaudDialog.dismiss();
                    itemBaud.setRightText(bauds[value]);
                    mControllerBean.getControllerSettingDto().getSettings().setBaudrate(value);
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomBaudDialog);
        }
//        mBottomBaudDialog.setDevice(mDevice);
        if(mControllerBean.getControllerSettingDto() != null && mControllerBean.getControllerSettingDto().getSettings() != null){
            mBottomBaudDialog.setSelectIndex(mControllerBean.getControllerSettingDto().getSettings().getBaudrate());
        }else{
            mBottomBaudDialog.setSelectIndex(0);
        }

        mBottomBaudDialog.show();
    }

    private void showBottomParityDialog() {
        if (mBottomParityDialog == null) {
            mBottomParityDialog = new BottomParityDialog(getContext());
            mBottomParityDialog.setLabel("校验方式");
            mBottomParityDialog.setDialogClickListener(new BottomParityDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int value) {
                    mBottomParityDialog.dismiss();
                    itemParity.setRightText(checkTypes[value]);
                    mControllerBean.getControllerSettingDto().getSettings().setChecktype(value);
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomParityDialog);
        }
//        mBottomParityDialog.setDevice(mDevice);
        if(mControllerBean.getControllerSettingDto() != null && mControllerBean.getControllerSettingDto().getSettings() != null){
            mBottomParityDialog.setSelectIndex(mControllerBean.getControllerSettingDto().getSettings().getChecktype());
        }else{
            mBottomParityDialog.setSelectIndex(0);
        }
        mBottomParityDialog.show();
    }

    private void showBottomStopbitDialog() {
        if (mBottomStopbitDialog == null) {
            mBottomStopbitDialog = new BottomStopbitDialog(getContext());
            mBottomStopbitDialog.setLabel("停止位");
            mBottomStopbitDialog.setDialogClickListener(new BottomStopbitDialog.DialogClickListener() {
                @Override
                public void onConfirmClick(int value) {
                    mBottomStopbitDialog.dismiss();
                    itemStopbit.setRightText(endMark[value]);
                    mControllerBean.getControllerSettingDto().getSettings().setEndmark(value);
                }
            });
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomStopbitDialog);
        }
//        mBottomBaudDialog.setDevice(mDevice);
        if(mControllerBean.getControllerSettingDto() != null && mControllerBean.getControllerSettingDto().getSettings() != null){
            mBottomStopbitDialog.setSelectIndex(mControllerBean.getControllerSettingDto().getSettings().getEndmark());
        }else{
            mBottomBaudDialog.setSelectIndex(0);
        }
        mBottomStopbitDialog.show();
    }
}
